package com.situ.mall.controller.front;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.situ.mall.common.ServerResponse;
import com.situ.mall.entity.User;
import com.situ.mall.service.IUserService;
import com.situ.mall.util.MD5Util;

@Controller
@RequestMapping("/user")
public class FrontUserController {


	@Autowired
	private IUserService userService;
	
	@RequestMapping("/register.shtml")
	@ResponseBody
	public ServerResponse register(HttpServletRequest req, HttpServletResponse resp) {
		String username = req.getParameter("username");
		String email = req.getParameter("email");
		String password = req.getParameter("password");
		
		ServerResponse serverResponse = null;
		User nameUser = userService.selectByName(username);
		
		if (null == nameUser) { // 用户不存在
			
			User emailUser = userService.selectByEmail(email);
			
			if (null != emailUser) {
				serverResponse = serverResponse.createError("邮箱已被注册");
				return serverResponse;
			}
			
			String enPassword = MD5Util.EncodeUtf8(password);
			
			User user = new User(username,enPassword,email);
			
			boolean isSuccess = userService.register(user);
			
			if (isSuccess) {
				serverResponse = ServerResponse.createSuccess("注册成功");
				return serverResponse;
			} else {
			    serverResponse = ServerResponse.createError("注册失败");
			    return serverResponse;
			}
		} else {
			serverResponse = ServerResponse.createError("用户名已存在");
			return serverResponse;
		}
	}
	
	@RequestMapping("/login.shtml")
	@ResponseBody
	public ServerResponse login(String username,String password,HttpSession session) {
		String enPassword = MD5Util.EncodeUtf8(password);
		return userService.login(username,enPassword,session);
	}
	
}
